package com.liry.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.liry.security.config.CacheManager;
import com.liry.security.domain.AuthConstant;
import com.liry.security.domain.po.RolePermission;
import com.liry.security.repository.RoleRepository;
import com.liry.security.service.RoleService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

/**
 * @author ALI
 * @since 2023/6/17
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl implements RoleService , InitializingBean {

    private CacheManager cacheManager;
    private RoleRepository roleRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        List<RolePermission> roleList = roleRepository.roleList();
        if (roleList.isEmpty()) {
            return;
        }
        Map<String, List<RolePermission>> permissionMap = roleList.stream().collect(Collectors.groupingBy(RolePermission::getRoleCode));
        for (Map.Entry<String, List<RolePermission>> entry : permissionMap.entrySet()) {
            String key = AuthConstant.ROLE_PRE + entry.getKey();
            List<String> collect = entry.getValue().stream().map(RolePermission::getPermissionUrl)
                                        .filter(StringUtils::isNoneBlank).collect(Collectors.toList());            String value = JSON.toJSONString(collect);
            cacheManager.set(key, value);
        }
    }
}
